
goog.provide('gaillard.HeaderFragment');

goog.require('goog.dom');
goog.require('goog.events.EventType');
goog.require('goog.dom.classes');
goog.require('goog.ui.Component');
goog.require('gaillard.Model');

/**
 *
 * @constructor
 * @extends {goog.ui.Component}
 */
gaillard.HeaderFragment = function(model) {
  goog.ui.Component.call(this);
   
  this.setModel(model);
};

goog.inherits(gaillard.HeaderFragment, goog.ui.Component);

gaillard.HeaderFragment.prototype.createDom = function() {
	throw Error('Impossible to create HeaderFragment from code');
};

gaillard.HeaderFragment.prototype.decorateInternal = function(element) {
	gaillard.HeaderFragment.superClass_.decorateInternal.call(this, element);
	
	this.addrestaurant_ = goog.dom.getElement('header-add-restaurant');
    this.parameters_ = goog.dom.getElement('header-parameters');
    this.parametersmenu_ = goog.dom.getElement('header-parameters-menu');
    this.researchform_ = goog.dom.getElement('header-research-form');
    this.searchquery_ = goog.dom.getElement('header-search-query');	
};

gaillard.HeaderFragment.prototype.enterDocument = function() {
	gaillard.HeaderFragment.superClass_.enterDocument.call(this);
    var eh = this.getHandler();
    
	if (this.addrestaurant_) {
		eh.listen(this.addrestaurant_, goog.events.EventType.CLICK, this.insertRestaurant_);
	}
	if (this.parameters_) {
		eh.listen(this.parameters_, goog.events.EventType.CLICK, this.showMenu_);    
	}
	
	eh.listen(this.researchform_, goog.events.EventType.SUBMIT, this.searchAddress_);
	
    eh.listen(this.getModel(), gaillard.Model.Datatype.ADDRESS, this.addressChanged_);
};


/**
 * Called when component's element is known to have been removed from the
 * document.
 */
gaillard.HeaderFragment.prototype.exitDocument = function() {
	gaillard.HeaderFragment.superClass_.exitDocument.call(this);
  
};

gaillard.HeaderFragment.prototype.insertRestaurant_ = function() {
    this.getModel().set(gaillard.Model.Datatype.OPEN_INSERT_RESTAURANT, true);
    
};

gaillard.HeaderFragment.prototype.showMenu_ = function (event) {	
	goog.dom.classes.add(this.parametersmenu_, 'open');
	this.getHandler().listenOnce(window, goog.events.EventType.CLICK, this.hideMenu_);
	event.stopPropagation();
	return false;
};

gaillard.HeaderFragment.prototype.hideMenu_ = function () {
	goog.dom.classes.remove(this.parametersmenu_, 'open');
};

gaillard.HeaderFragment.prototype.searchAddress_ = function (event) {
	var req = this.searchquery_.value;
	this.getModel().searchAddress(req);
    event.preventDefault();
	return false;
};

gaillard.HeaderFragment.prototype.addressChanged_ = function () {
    var address = this.getModel().get(gaillard.Model.Datatype.ADDRESS);
	this.searchquery_.value = address.formatted_address;
};
